package com.ruoyi.module.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.ruoyi.common.core.domain.event.UserRegisteredEvent;
import com.ruoyi.module.service.IDictBookUserService;

/**
 * 用户注册事件监听器
 * 处理用户注册后的相关操作
 * 
 * @author ruoyi
 */
@Component
public class UserRegisteredEventListener
{
    private static final Logger log = LoggerFactory.getLogger(UserRegisteredEventListener.class);

    @Autowired
    private IDictBookUserService dictBookUserService;

    /**
     * 监听用户注册事件，自动为新用户分配免费词典
     * 
     * @param event 用户注册事件
     */
    @EventListener
    @Async
    public void onUserRegistered(UserRegisteredEvent event)
    {
        Long userId = event.getUserId();
        String username = event.getUsername();
        
        try
        {
            log.info("检测到用户注册事件: userId={}, username={}", userId, username);
            
            // 为新用户分配所有免费词典
            int count = dictBookUserService.assignFreeDictBooksToUser(userId);
            
            if (count > 0)
            {
                log.info("成功为新用户 [{}] 自动分配了 {} 个免费词典", username, count);
            }
            else
            {
                log.warn("未能为新用户 [{}] 分配免费词典，可能没有配置免费词典", username);
            }
        }
        catch (Exception e)
        {
            // 分配词典失败不影响注册流程，只记录日志
            log.error("为新用户 [{}] 分配免费词典失败: {}", username, e.getMessage(), e);
        }
    }
}

